/**
 * Created by DXX520 on 2017/2/9.
 */
(function (angular) {
    var app=angular.module('todoApp.service',[]);
    //创建一个服务,相当于后台数据,送给控制台
    app.service('storageService', function ($window,$filter) {
        var todoList=angular.fromJson($window.localStorage.getItem('todoList')||"[]");
        //返回数据,这时候的数据和todoList的地址不一样
        this.getTodo= function () {
            return todoList
        }
        //增加
        this.addTodo= function (text) {
            todoList.push({id:Math.random(),text:text,isCompleted:false})
            this.saveTodo();
        }
        //保存
        this.saveTodo= function () {
            $window.localStorage.setItem('todoList',angular.toJson(todoList));
        }

        //修改,这先保持疑惑
        this.editTodo= function () {
            this.saveTodo();
        }
        //删除
        this.delTodo= function (todo) {
          var index=todoList.indexOf(todo);
            todoList.splice(index,1);
            this.saveTodo();
        }
        //清除已完成数据
        this.clearCompleted= function () {
            todoList=$filter('filter')(todoList,{isCompleted:false})
            this.saveTodo();
            return todoList;
        }
        //全选切换
        this.changeAll= function (toggleAll) {
            angular.forEach(todoList, function (todo) {
                todo.isCompleted=toggleAll;
            })
            this.saveTodo();
            return todoList;
        }
    })

})(angular)